package com.pay.online.online_pay

import android.annotation.SuppressLint
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import com.pay.online.online_pay.alipay.AlipayPay
import com.pay.online.online_pay.onlinepay.OnlinePayResultInfo
import com.pay.online.online_pay.onlinepay.OnlinePayResultType
import com.pay.online.online_pay.onlinepay.OnlinePayType
import com.pay.online.online_pay.onlinepay.toOnlinePayType
import com.pay.online.online_pay.wxpay.WechatPay
import com.pay.online.online_pay.wxpay.WechatPayParams
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import org.json.JSONObject

/** OnlinePayPlugin */
class OnlinePayPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {

    companion object {

        const val ACTION_NOTIFY_PAY_RESULT = "notify_pay_result"

        /** 获取或设置微信支付ID **/
        var wxAppId: String? = null
            private set

        /**
         * 初始化操作
         * @param wxAppId 微信支付ID
         */
        @JvmStatic
        @JvmOverloads
        fun initialize(wxAppId: String? = null) {
            Companion.wxAppId = wxAppId
        }

    }

    private lateinit var activity: Activity

    private lateinit var channel: MethodChannel

    private val alipay by lazy {
        AlipayPay.getInstance()?.apply {
            setOnNotifyPayResultListener { result ->
                callback?.success(result.toMap())
                callback = null
            }
        }
    }

    private val wxPay by lazy { WechatPay.getInstance() }

    private val payResultReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == ACTION_NOTIFY_PAY_RESULT) {
                    val payResult = when {
                        Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU ->
                            intent.getParcelableExtra(
                                "pay_result",
                                OnlinePayResultInfo::class.java
                            )
                        else -> intent.getParcelableExtra("pay_result")
                    }
                    callback?.success(payResult?.toMap())
                    callback = null
                }
            }
        }
    }

    private var callback: Result? = null

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "online_pay")
        channel.setMethodCallHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity.apply {
            registerReceiver(payResultReceiver, IntentFilter(ACTION_NOTIFY_PAY_RESULT))
        }
    }

    override fun onDetachedFromActivityForConfigChanges() {}

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {}

    override fun onDetachedFromActivity() {
        activity.unregisterReceiver(payResultReceiver)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        when (call.method) {
            "getPlatformVersion" ->
                result.success("Android ${Build.VERSION.RELEASE}")
            "initialize" ->
                initialize(call.argument("wxAppId"))
            "startPay" -> startPay(call, result)
            "isWechatInstalled" ->
                result.success(WechatPay.getInstance()?.isWXAppInstalled ?: false)
            else -> result.notImplemented()
        }
    }

    /**
     * 启动在线支付
     * @param call 方法Call
     */
    private fun startPay(call: MethodCall, result: Result) {
        callback = result //赋值结果反馈对接
        val onlinePayType = call.argument<String>("type")
            ?.toOnlinePayType()
        val payInfo = call.argument<String>("payInfo")
        if (payInfo.isNullOrEmpty()) {
            callback?.success(
                OnlinePayResultInfo(
                    onlinePayType = onlinePayType,
                    resultType = OnlinePayResultType.Error,
                    message = "错误：支付参数不能为空"
                ).toMap()
            )
            callback = null
            return
        }
        when (onlinePayType) {
            OnlinePayType.Alipay -> alipay?.startPay(activity, payInfo)
            // 微信支付的实体类使用JSONObject方式获取
            OnlinePayType.WechatPay ->
                wxPay?.startPay(WechatPayParams.fromJsonObject(JSONObject(payInfo)))
            else -> {
                callback = null
                result.error("ONLINE_PAY_TYPE_ERROR", "错误：未知支付类型", null)
            }
        }
    }

}
